import { Suspense, useMemo } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
/* -------------------------------------------------------- Function -- */
import { getRedirect, getRootUrl, existHttp } from './utils'
/* -------------------------------------------------------- Sync Component -- */
/* -------------------------------------------------------- Declare -- */
const { $fn, $lazy } = window
/**
 * 模块子路由配置
 * @param {Array} data		# 菜单数据
 * @param {String} rootPath	# 根目录，如： /main
 * @param {String} redirect	# 自定义重定向的路径
 * @data { path:'css/style', component:'', children:{ path:'css/style/font', component:'' } }
 * @return {Component} 路由组件
 */
const DeepRouter = ({ data, rootPath=window.$config.menu.root, redirect, childHasRootPath }) => {
	const deep = ({ data, hasChild}) => {
		if( !redirect){ redirect= getRedirect(data) }
		return (
			<>
				{
					data.map(({ children, name, path, child, outlet, component })=>{
						let key = path + '/' + Date.now()
						let props = { path:name + (outlet ? '/*' : '') }
						{/* 只有路由没有组件 */}
						if($fn.hasArray(children)) return <Route {...props} key={key} path={name + '/*'}>{ deep({ data:children }) }</Route>
						{/* http 外链 */}
						if( existHttp(path) ) return null
						{/* 获取组件 */}
						if( $fn.isNotEmpty(component) ){
							if( component.startsWith('/') ) component = component.replace(/^\//g, '')
							if( rootPath ) component = rootPath + '/' + component
						}else{
							component = path
							if( component && component.includes('/dict-') ) component = rootPath ? '/' + rootPath + '/_s/dict' : '/_s/dict'
							if( rootPath || ( hasChild && childHasRootPath) ){
								component = component ? component.replace(/^\//g, '') : null
							}else{
								const rootUrl = getRootUrl(component)
								component = component.replace(new RegExp(`^${rootUrl}/`,'g'), '')
							}
						}
						props = component ? { ...props, Component: $lazy.router( component ) } : null
						{/* 每级路由都有组件 */}
						if($fn.hasArray(child)) return <Route {...props} key={key}>{ deep({ data:child, hasChild:true }) }</Route>
						
						{/* 基本路由 */}
						return <Route key={path} {...props} />
					})
				}
				{/* 重定向 */}
				{ (redirect&&!hasChild) && <Route path={ name } element={ <Navigate to={redirect} replace /> } /> }
				{/* 404 */}
				{ !hasChild && <Route path='*' Component={ $lazy.router('404') } /> }
			</>
		)
	}
	return useMemo(()=><Suspense><Routes>{ $fn.hasArray(data) ? deep({ data }) : null }</Routes></Suspense>,[ data ]) // eslint-disable-line
}


export default DeepRouter